package cn.it.shop.service.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.it.shop.pojo.User;
/*
 * 用来判断用户是否登录的过滤器
 * */
public class UserFilter implements Filter {

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		// 判断用户是否登录
		HttpServletRequest req=(HttpServletRequest)request;
		HttpSession session = req.getSession();
		User user=(User)session.getAttribute("user");
		if(user==null){
			// 非法访问, 保存当前请求的地址,后面登录成功则要跳转此地址
			session.setAttribute("goURL", req.getServletPath());
//			System.out.println(req.getServletPath());
//			System.out.println(req.getRequestURI());
//			System.out.println(req.getRequestURL());
			session.setAttribute("error", "请登录!");
			HttpServletResponse res=(HttpServletResponse)response;
			res.sendRedirect(req.getContextPath() + "/ulogin.jsp");
		}else{
			// 跳转到下一个过滤器, 如果没有则跳转到目标页面
			chain.doFilter(request, response);
		}
	}

	@Override
	public void init(FilterConfig arg0) throws ServletException {

	}

}
